/*
 * @Author: xiehangyun 
 * @Date: 2025-05-15 10:11:06 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2025-09-05 16:39:10
 */

import { Tour } from '@nutui/nutui-react-taro';
import { PageContainer } from '@tarojs/components';
import Taro, { useDidHide, useDidShow, useUnload } from '@tarojs/taro';
import { toJS } from 'mobx';
import { observer } from "mobx-react-lite";
import { ReactNode, useRef, useState } from 'react';
import Api from 'src/api/Api';
import utilsApi from 'src/api/utilsApi';
import PageLayer from 'src/components/PageLayer/PageLayer';
import categoryStore from 'src/pages/Category/categoryStore';
import goOnPreDesignStore from 'src/pages/Index/GoOnPreDesign/goOnPreDesignStore';
import utils from 'src/utils/utils';
import utilsStore from 'src/utils/utilsStore';
import { GoodsData } from 'types/type';
import styles from './design.module.less'; // 修改为模块化样式
import BottomBtns from './designComponent/BottomBtns/BottomBtns';
import CenterAlign from './designComponent/CenterAlign/CenterAlign';
import ChangeLayer from './designComponent/ChangeLayer/ChangeLayer';
import ComponentSelect from './designComponent/ComponentSelect/ComponentSelect';
import CropModel from './designComponent/CropModel/CropModel';
import CutoutModel from './designComponent/CutoutModel/CutoutModel';
import Designer from './designComponent/Designer/Designer';
import designerRender from './designComponent/Designer/designerRender';
import designerStore from './designComponent/Designer/designerStore';
import DesignerBtns from './designComponent/DesignerBtns/DesignerBtns';
import FineTuning from './designComponent/FineTuning/FineTuning';
import Flip from './designComponent/Flip/Flip';
import ImageModel from './designComponent/ImageModel/ImageModel';
import LayerList from './designComponent/LayerList/LayerList';
import LeftTop from './designComponent/LeftTop/LeftTop';
import MaskModel from './designComponent/MaskModel/MaskModel';
import perview3der from './designComponent/RightTop/PreView2D3D/perview3der';
import RightTop from './designComponent/RightTop/RightTop';
import setEditorDate from './designComponent/setEditorDate';
import StickerModel from './designComponent/StickerModel/StickerModel';
import TemplateModel from './designComponent/TemplateModel/TemplateModel';
import TextModel from './designComponent/TextModel/TextModel';
import BlurWarn from './designComponent/BlurWarn/BlurWarn';
import blurWarnStore from './designComponent/BlurWarn/blurWarnStore';
import AiImage from './designComponent/AiImage/AiImage';

interface Iprops {
    children?: ReactNode
}

// 设计
const Design = observer((props: Iprops) => {

    const [showTour, setShowTour] = useState(false);
    const [showPageContainer, setShowPageContainer] = useState<boolean>(true);

    // 对应 onShow
    useDidShow(() => {
        const productId = Taro.getStorageSync('designer_productId'); //商品id
        const productNegativeId = Taro.getStorageSync('designer_productNegativeId'); //底板id
        const productDesign = Taro.getStorageSync('designer_productDesign');
        const designName = Taro.getStorageSync('designer_name'); // 设计名称
        const time = Taro.getStorageSync('designer_time');
        const size = Taro.getStorageSync('designer_size'); // 规格
        const color = Taro.getStorageSync('designer_color'); // 颜色
        const colorValue = Taro.getStorageSync('designer_colorValue'); // 颜色值
        const needupload = Taro.getStorageSync('designer_needupload'); //是否需要更新设计器

        // console.log('ppid', ppid, 'designData', designData, 'daltime', new Date().valueOf() - time);

        // 判断一下这些数据的存储事件如果的 5s内的都算有效
        if (needupload) {
            Taro.setStorageSync('designer_needupload', false);
            // 只有在需要更新编辑器时才提前清空一下
            designerRender.clear();
            setEditorDate({
                productId,
                productNegativeId,
                productDesign,
                designName,
                color,
                colorValue
            });
        } else {
            setTimeout(() => {
                designerRender.requestRenderAll();
            }, 1000);
        }

        // 关闭切换款式的状态
        categoryStore.setIsSwitchKua(false);

        setTimeout(() => {
            if (utilsStore.showTour4) {
                utilsStore.setShowTour4(false);
                setShowTour(true);
            }
        }, 1500);

    });

    useDidHide(() => {
        console.log('onHide');
    });

    // Taro.removeStorageSync('temp_designer');

    useUnload(() => {
        console.log('Design.tsx onUnload');
        setShowTour(false);
        designerStore.setAmplify(false);
    });

    // 退出网页
    const back = () => {
        // 询问是否离开
        Taro.showModal({
            title: '提示',
            content: '确定要离开吗？',
            success: async (res) => {
                if (res.confirm) {
                    setHasContainer(false);
                    setTimeout(() => {
                        Taro.navigateBack();
                    }, 200);

                    const fontThumbFile = await perview3der.getFrontThumb();
                    const backThumbFile = await perview3der.getBackThumb();
                    console.log('fontThumbFile', fontThumbFile, 'backThumbFile', backThumbFile);
                    const fontThumbUrl = fontThumbFile ? await utilsApi.uploadOss(fontThumbFile, Api.ossDirectory) : fontThumbFile;
                    const backThumbUrl = backThumbFile ? await utilsApi.uploadOss(backThumbFile, Api.ossDirectory) : backThumbFile;
                    console.log('fontThumbUrl', fontThumbUrl, 'backThumbUrl', backThumbUrl);

                    // 设计数据
                    const productDesign: GoodsData["productData"] = {
                        ...toJS(designerStore.designData),
                        thumbs: [fontThumbUrl, backThumbUrl], // 商品图片数组
                    };

                    const productId = Taro.getStorageSync('designer_productId'); //商品id
                    const productNegativeId = Taro.getStorageSync('designer_productNegativeId'); //底板id
                    const designName = Taro.getStorageSync('designer_name'); // 设计名称
                    const time = Taro.getStorageSync('designer_time');
                    const size = Taro.getStorageSync('designer_size'); // 规格
                    const color = Taro.getStorageSync('designer_color'); // 颜色
                    const colorValue = Taro.getStorageSync('designer_colorValue'); // 颜色值
                    const needupload = Taro.getStorageSync('designer_needupload'); //是否需要更新设计器

                    const { selectColor, selectColorValue } = designerStore;
                    console.log('selectColor', selectColor, 'selectColorValue', selectColorValue);
                    console.log("save temp_designer");

                    goOnPreDesignStore.setTemp_designer({
                        productId,//商品id
                        productNegativeId,//底板id
                        productDesign,//具体商品设计json
                        designName,
                        size,//尺码
                        color: selectColor,//颜色名
                        colorValue: selectColorValue,//颜色值
                    });

                } else {
                    showConfirm.current = false;
                }
            }
        });
    }


    const touchPosition = useRef<{ x: number, y: number }>({ x: 0, y: 0 });
    const hasMove = useRef<boolean>(false);
    const hasRotation = useRef<boolean>(false);
    const initDistance = useRef<number>(0); // 初始的双指距离
    const initAngle = useRef<number>(0); // 初始的双指角度

    //是否显示确认弹窗, 避免显示多个确认框
    const showConfirm = useRef(false);
    // 是否需要PageContainer
    const [hasContainer, setHasContainer] = useState(true);

    const children = (
        <PageLayer
            showBack={true}
            hasTabBar={false}
            className={styles.design}
            onBack={back}
            onTouchStart={(e) => {
                e.stopPropagation();
                e.preventDefault();
                // console.log('ontouchstart', e.touches.length);
                touchPosition.current.x = e.touches[0].clientX;
                touchPosition.current.y = e.touches[0].clientY;
                // 如果是双指触摸，则计算初始距离和角度
                if (e.touches.length === 1) {
                    hasMove.current = false;
                    hasRotation.current = false;
                    // if (e.target === e.currentTarget) {
                    //     designerRender.onTouchStart(e);
                    // }
                } else if (e.touches.length === 2) {
                    const pointA = e.touches[0];
                    const pointB = e.touches[1];
                    const xDist = pointB.clientX - pointA.clientX;
                    const yDist = pointB.clientY - pointA.clientY;
                    initDistance.current = Math.sqrt(xDist * xDist + yDist * yDist);
                    const x = pointA.clientX - pointB.clientX;
                    const y = pointA.clientY - pointB.clientY;
                    initAngle.current = Math.atan2(y, x) * 180 / Math.PI;
                }

            }}
            onTouchMove={(e) => {
                e.stopPropagation();
                e.preventDefault();
                // console.log('ontouchmove', e.touches.length);
                const activeObject = designerRender.getActiveObject();
                var target = designerRender.findTarget(e);

                if (e.touches.length === 1) {

                    if (e.target === e.currentTarget && !target && activeObject && !hasRotation.current) {
                        const offsetX = e.touches[0].clientX - touchPosition.current.x;
                        const offsetY = e.touches[0].clientY - touchPosition.current.y;

                        if (activeObject.lockMovementX) {

                        } else {
                            activeObject.set({
                                left: activeObject.left + offsetX,
                                top: activeObject.top + offsetY,
                            });
                            hasMove.current = true;
                        }

                        designerRender.requestRenderAll();
                        touchPosition.current.x = e.touches[0].clientX;
                        touchPosition.current.y = e.touches[0].clientY;
                    } else {
                        // designerRender.onMouseMove(e);
                    }

                } else if (e.touches.length === 2 && activeObject) {
                    const pointA = e.touches[0];
                    const pointB = e.touches[1];
                    const xDist = pointB.clientX - pointA.clientX;
                    const yDist = pointB.clientY - pointA.clientY;
                    const currentDistance = Math.sqrt(xDist * xDist + yDist * yDist);
                    const scale = currentDistance / initDistance.current;
                    initDistance.current = currentDistance;

                    const x = pointA.clientX - pointB.clientX;
                    const y = pointA.clientY - pointB.clientY;
                    const currentAngle = Math.atan2(y, x) * 180 / Math.PI;
                    const angleDiff = currentAngle - initAngle.current;
                    initAngle.current = currentAngle;

                    if (activeObject.lockMovementX) {

                    } else {
                        activeObject.set({
                            'scaleX': activeObject.scaleX * scale,
                            'scaleY': activeObject.scaleX * scale,
                            'angle': activeObject.angle + angleDiff
                        });
                        hasMove.current = true;
                        hasRotation.current = true;
                    }
                    designerRender.requestRenderAll();
                }
            }}
            onTouchEnd={(e) => {
                e.stopPropagation();
                e.preventDefault();
                // console.log('ontouchend', e.touches.length);
                if (e.touches.length === 1) {
                    // const activeObject = designerRender.getActiveObject();
                    // if (activeObject) {
                    //     designerRender._setupCurrentTransform(e, activeObject, true);
                    // }

                    // 结束双指缩放时,要检测一下 模糊
                    const activeObject = designerRender.getActiveObject();
                    if (["image", "Image"].includes(activeObject.type)) {
                        const isBlur = activeObject.isBlur();
                        if (isBlur) {
                            blurWarnStore.show();
                        }
                        console.log('isBlur', isBlur);
                    }

                } else if (
                    e.touches.length === 0 &&
                    e.target === e.currentTarget
                ) {
                    if (hasMove.current || hasRotation.current) {
                        designerRender.recordHistory();
                    } else {
                        //判断 事件对象里面的点击对象是不是自己
                        // 点击空白处取消选中状态
                        designerRender.discardActiveObject();
                        designerRender.mainTouchId = undefined;
                        designerRender.requestRenderAll();
                    }
                }

            }}
        >

            {/* 左上角的款式和颜色 */}
            < LeftTop />

            {/* 右上角的预览和保存 */}
            < RightTop />

            {/* 设计器 */}
            < Designer />

            {/* 部位选择组件 */}
            < ComponentSelect />

            {/* ai生图按钮  */}
            {/* <AiImage /> */}

            {/* 模糊警告提示组件 */}
            < BlurWarn />

            {/* 设计器的按钮 */}
            < DesignerBtns />

            {/* 编辑器的底部按钮 */}
            < BottomBtns />

            {/* 元素的通用功能 有选中元素的时候就会出现 */}
            {/* < ObjectsBtns /> */}

            {/* 调整层级 */}
            < ChangeLayer />

            {/* 居中对齐 */}
            < CenterAlign />

            {/* 调整层级 */}
            < FineTuning />

            {/* 翻转 */}
            < Flip />

            {/* 设计模版 */}
            < TemplateModel />

            {/* 贴纸弹窗 */}
            < StickerModel />

            {/* 字体编辑 */}
            < TextModel />

            {/* 图片弹窗 */}
            < ImageModel />

            {/* 遮罩弹窗 */}
            <MaskModel />

            {/* 图层 */}
            < LayerList />

            {/* 裁剪图片组件 */}
            <CropModel />

            {/* 抠图弹窗组件 */}
            <CutoutModel />

            <Tour
                className="nut-custom-tour"
                visible={showTour}
                onClose={() => {
                    utilsStore.setShowTour4(false);
                    setShowTour(false);
                }}
                list={[
                    {
                        content: '4.设计完成后,点击保存按钮',
                        target: 'save'
                    }
                ]}
                location="bottom-end"
                offset={[0, 0]}
                maskWidth={utils.rpx2px(120)}
                maskHeight={utils.rpx2px(60)}
            />

        </PageLayer >
    );

    if (!hasContainer) {
        return children;
    } else {
        return (
            <PageContainer
                show={showPageContainer}
                position='right'
                // 把离开相关的事件都用上
                onBeforeLeave={async () => {
                    if (!showConfirm.current) {
                        showConfirm.current = true;
                        await back();
                    }
                    setShowPageContainer(false);
                    await new Promise(resolve => setTimeout(resolve, 200));
                    setShowPageContainer(true);
                }}
            >
                {children}
            </PageContainer>
        );
    }
});

export default Design;



